package com.ms.oschina.util;

import java.util.List;

import android.graphics.Color;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.ms.oschina.R;
import com.ms.oschina.base.AppContext;
import com.ms.oschina.bean.Tweet;
import com.ms.oschina.bean.User;
import com.ms.oschina.view.NoUnderLineClickableSpan;
import com.ms.oschina.view.TextViewFixTouchConsume;

/**
 * 富文本帮助器 ： 表情，文字点赞效果，@。
 * 
 * @author Administrator
 * 
 */
public class RichTextHelper {

	private static int skipIndex;

	private static int color;
	static {
		color = UiUtils.getContext().getResources().getColor(R.color.green);
	}

	/**
	 * @param tv
	 * @param maxShowCount
	 *            最大显示赞的个数
	 * @param data
	 *            哪个动弹信心设置
	 * @param color
	 *            赞的颜色
	 */
	public static void showLike(TextView tv, int maxShowCount, Tweet data,
			int color) {
		tv.setText("");
		int likeCount = data.getLikeCount();
		if (likeCount == 0) {
			tv.setVisibility(View.GONE);
		} else {
			tv.setVisibility(View.VISIBLE);
			setlikeList(tv, data, likeCount, maxShowCount);
		}
	}

	/**
	 * 设置复合文本 包括： @ 表情、网址、话题
	 * 
	 * @param tv
	 * @param str
	 */
	public static void setTextRecombinationContent(TextView tv, final String str) {
		// 话题#谈一谈#、 链接(跳转activity使用webview解析)、 表情、@
		// 使用正则表达式判断 是否是话题 ，是否是表情

		if (TextUtils.isEmpty(str)) {
			return;
		}
		// 防止复用
		tv.setText("");
		skipIndex = -1;

		if (str.length() < 3 && !str.contains("#") && !str.contains("{")
				&& !str.contains("http://") && !str.contains("@")) {
			tv.setText(str);
			return;
		}

		// boolean matcheTopic = Pattern.matches("#.+#", str);
		// boolean matcheEmoji = str.matches("{.+}");
		// 不根据正则去做匹配， 遍历字符串出现的位置做匹配规则
		tv.setMovementMethod(TextViewFixTouchConsume.LocalLinkMovementMethod
				.getInstance());// 不加他文字点击事件无效
		Editable editableText = tv.getEditableText();
		for (int i = 0; i < str.length(); i++) {
			if (i < skipIndex) {
				continue;
			}

			String string = String.valueOf(str.charAt(i));
			if (string.equals("#")) {
				String topic = checkStr("#", string, str, i, editableText, tv);

				if (topic != null) {// 添加话题
					ForegroundColorSpan span = new ForegroundColorSpan(
							Color.BLUE);
					RichTextHelper.addSpan(tv, topic, span,
							new TextClickableSpan(topic));
				}

			} else if (string.equals("[")) {// 表情
				String topic = checkStr("]", string, str, i, editableText, tv);

				if (topic != null) {// 添加表情
					//
					int resId = EmojiUtils.getEmojiResId(topic);
					if (resId != -1) {
						ImageSpan span = EmojiUtils
								.getEmojiImgSpan(
										resId,
										UiUtils.getDimensionPixelSize(R.dimen.space_20));
						RichTextHelper.addSpan(tv, topic, span,
								new TextClickableSpan(topic));
					}
				}
			} else if (string.equals("@")) {// 暂时不做
				String at = getAt(str);
				skipIndex = at.length() + i;
				ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
				RichTextHelper.addSpan(tv, at, span, new TextClickableSpan(at));
			} else if (string.equalsIgnoreCase("h")) {// http
				// 截取H后空格或者中文前一个
				if (str.contains("http")) {
					String httpUrl = getHttpUrl(str);
					skipIndex = httpUrl.length() + i;
					URLSpan span = new URLSpan(httpUrl);
					RichTextHelper.addSpan(tv, httpUrl, span,
							new TextClickableSpan(httpUrl));
				}
			} else {
				tv.append(string);
			}
		}
	}

	/**
	 * 通过一组字符串，返回字符串里的网址
	 * 
	 * @param str
	 * @return
	 */
	private static String getHttpUrl(String str) {
		str = str.toLowerCase();
		int indexOf = str.indexOf("http");
		String tempStr = str.substring(indexOf);

		int to = 0;
		for (int i = 0; i < tempStr.length(); i++) {
			String string = String.valueOf(tempStr.charAt(i));
			if (string.equals(" ") || StringUtils.isChineseCharacter(string)
					|| i == tempStr.length() - 1) {
				to = i;
				break;
			}
		}
		return str.substring(indexOf, indexOf + to + 1);
	}

	/**
	 * 通过一组字符串，返回字符串里的网址
	 * 
	 * @param str
	 * @return
	 */
	private static String getAt(String str) {
		str = str.toLowerCase();
		int indexOf = str.indexOf("@");
		String tempStr = str.substring(indexOf);

		int to = 0;
		for (int i = 0; i < tempStr.length(); i++) {
			String string = String.valueOf(tempStr.charAt(i));
			if (string.equals(" ") || i == tempStr.length() - 1) {
				to = i;
				break;
			}
		}
		return str.substring(indexOf, indexOf + to);
	}

	/**
	 * @param rule
	 *            查找整个字符串结束出现的字符
	 * @param str
	 *            查找整个字符串开始出现的字符
	 * @param fullStr
	 * @param index
	 * @param editableText
	 * @param tv
	 * @return 开始的字符到结束出现的字符
	 */
	private static String checkStr(String rule, String str, String fullStr,
			int index, Editable editableText, TextView tv) {

		int indexOf = fullStr.indexOf(rule, index + 1);
		if (indexOf == -1) {// 不匹配规则
			tv.append(str);
		} else {
			skipIndex = indexOf + 1;
			return fullStr.substring(index, skipIndex);
		}
		return null;
	}

	/***
	 * 给文字添加span
	 * 
	 * @param tv
	 * @param str
	 * @param span
	 * @param clickableSpan
	 */
	public static void addSpan(TextView tv, final String str,
			CharacterStyle span, NoUnderLineClickableSpan clickableSpan) {
		SpannableString spanString = new SpannableString(str);
		if (!(span instanceof ImageSpan)) {// 设置文字点击事件
			spanString.setSpan(clickableSpan, 0, str.length(),
					Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		}
		spanString.setSpan(span, 0, str.length(),
				Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		tv.append(spanString);
	}

	private static void setlikeList(TextView tv, Tweet data, int showLikeCount,
			int maxShowCount) {

		tv.setMovementMethod(TextViewFixTouchConsume.LocalLinkMovementMethod
				.getInstance());// 不加他文字点击事件无效
		List<User> likeUser = data.getLikeUser();
		for (int i = 0; i < likeUser.size(); i++) {
			final User user = likeUser.get(i);
			if (user != null) {// 设置点赞列表
				if (i < maxShowCount) {
					// 拼接span
					String text = user.getName();
					ForegroundColorSpan span = new ForegroundColorSpan(color);
					addSpan(tv, text, span, new NoUnderLineClickableSpan() {
						@Override
						public void onClick(View widget) {
							UiUtils.showToast("" + user.getId());
						}
					});
					if (i != maxShowCount - 1 && i != showLikeCount - 1) {// 当前user不是最后一个点赞
						tv.append("、");
					}
					continue;
				}
			}
			break;
		}

		if (showLikeCount > maxShowCount && showLikeCount > 1) {// 等XX人 觉得很赞
			tv.append("等");
			ForegroundColorSpan span = new ForegroundColorSpan(color);
			addSpan(tv, showLikeCount + "人", span, new NoUnderLineClickableSpan() {
				@Override
				public void onClick(View widget) {
					UiUtils.showToast("进入点赞列表");
				}
			});
		}

		tv.append("觉得很赞");
	}

	public static class TextClickableSpan extends NoUnderLineClickableSpan {

		private String topic;

		public TextClickableSpan(String topic) {
			this.topic = topic;
		}

		@Override
		public void onClick(View widget) {
			UiUtils.showToast(topic);
		}
	}

	public static void likeAni(ImageView ivLike) {
		ScaleAnimation sa = new ScaleAnimation(1, 1.2f, 1, 1.2f, 0.5f, 0.5f);
		sa.setDuration(300);
		ivLike.startAnimation(sa);
	};

	public static void delCurLike(TextView tvTweetLikeInfo, String userName) {
		String string = tvTweetLikeInfo.getText().toString();
		int index = string.indexOf(userName);
		if (index != -1) {
			tvTweetLikeInfo.getEditableText().delete(index, userName.length());
		}
	};

	static SpannableString curSpanString = null;

	public static void insertCurLike(TextView tvTweetLikeInfo, String userName) {
		Editable editableText = tvTweetLikeInfo.getEditableText();

		// AppContext.getUid()
		ForegroundColorSpan span = new ForegroundColorSpan(color);
		SpannableString spanString = new SpannableString(userName);
		spanString.setSpan(span, 0, userName.length(), Spannable.SPAN_USER);
		curSpanString = spanString;
		if (editableText == null) {// 没有点过赞
			tvTweetLikeInfo.append(spanString);
		} else {
			tvTweetLikeInfo.getEditableText().insert(0, spanString);
		}

		// 添加删除标记
		tvTweetLikeInfo.setTag("");
	};

}
